package org.wpahs.ahn.rssfeed;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Base64;
import android.util.Log;
import android.webkit.URLUtil;

import org.apache.http.HttpEntity;
import org.wpahs.ahn.rssfeed.DB.DBFeedItem;
import org.wpahs.ahn.rssfeed.DB.DBMyFeed;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;

/**
 * Created by dgambone on 02/17/2015.
 */
public class ImageFinder extends AsyncTask<Void, Void, ImageFinder.OpenGraphInfo> {
    private FeedItem mFeedItem = null;
    private Context context = null;

    public ImageFinder(FeedItem item,Context context) {
        mFeedItem = item;
        this.context = context;
    }

    public class OpenGraphInfo{
        public String ogImage;
        public String ogImageUrl;
        public String ogSiteName;
        public String ogDescription;
    }

    @Override
    protected OpenGraphInfo doInBackground(Void... params) {
        //first check the fed item's url. See if the page
        //contains an "og:image" meta tag.  If it does.
        //we'll use it.  Else.  We're try to grab from the feed item
        OpenGraphInfo info = new OpenGraphInfo();
        Log.i("ImageDownloader", "Looking to download image for " + mFeedItem.getTitle());
        info=findOgInfo(mFeedItem.getLink(),info);

        //check to see if ogImageUrl is null.  if its.  try another option.
        if(info.ogImageUrl == null){
            Log.e("ImageDownloader", "Failed og:image for " + mFeedItem.getTitle());

        }
        return info;
    }

    private OpenGraphInfo findOgInfo(String url,OpenGraphInfo info){
        //BufferedReader r = null;
        try {
            Log.i("findOGImageUrl",url);
            URL urlConnection = new URL(url);

            HttpURLConnection connection = null;
            if(!URLUtil.isHttpsUrl(url)){
                connection = (HttpURLConnection) urlConnection
                        .openConnection();

            }else{
                connection = (HttpsURLConnection) urlConnection
                        .openConnection();
            }

            connection.setDoInput(true);
            connection.connect();
            InputStream input = connection.getInputStream();
            BufferedReader r = new BufferedReader(new InputStreamReader(input));

            String line;
            String metaStart = "<meta";
            String end = ">";
            String propertyAttrib = "property=\"";
            while ((line = r.readLine()) != null) {
                int endPos = 0;
                int startPos = 0;
                while ((startPos = line.indexOf(metaStart, endPos)) != -1) {
                    endPos = line.indexOf(end, startPos + metaStart.length());
                    if (endPos != -1) {
                        String imgElement =
                                imgElement = line.substring(startPos, endPos);
                        String propertyValue = getAttributeValue(imgElement, "property");
                        if (propertyValue != null && propertyValue.equals("og:image")) {
                            String contentValue = getAttributeValue(imgElement, "content");
                            if (contentValue != null && contentValue.toLowerCase().contains("http")) {
                                info.ogImageUrl = contentValue;
                                Log.i("og:image", contentValue);
                                break;
                            }
                        }else if(propertyValue != null && propertyValue.equals("og:site_name")){
                            String contentValue = getAttributeValue(imgElement, "content");
                            if (contentValue != null ) {
                                info.ogSiteName = contentValue;
                                Log.i("og:site_name", contentValue);
                                break;
                            }
                        }else if(propertyValue != null && propertyValue.equals("og:description")){
                            String contentValue = getAttributeValue(imgElement, "content");
                            if (contentValue != null ) {
                                info.ogDescription = contentValue;
                                Log.i("og:description", contentValue);
                                break;
                            }
                        }
                    }else{
                        break;
                    }
                }
                //Log.i("tryParse-urlToImage",urlToImage);
            }


        }catch (IOException ioEx) {
            Log.e("findOGImageUrl", "" +
                            (ioEx.getMessage() != null ? ioEx.getMessage() : "Mystery Error")
            );
        }catch (Exception ex){
            Log.e("findOGImageUrl", "" +
                            (ex.getMessage() != null ? ex.getMessage() : "Mystery Error")
            );
        }
        return info;
    }


    @Override
    protected void onPostExecute(OpenGraphInfo result) {
        super.onPostExecute(result);

            // set the image in the db
        DBMyFeed dbMf = new DBMyFeed(context);
            try {

                if(result.ogImageUrl != null) {
                    Image img = new Image();
                    img.setId(mFeedItem.getFeedId());
                    img.setSubId(mFeedItem.getItemId());
                    img.setUrl(result.ogImageUrl);
                    img.setDownloadType(Downloader.DownloadType.FeedItemImage);
                    Downloader.addImageToQueue(this.context,img);
                }

                MyFeed myFeed = dbMf.getFeed(mFeedItem.getFeedId());
                if((myFeed.getTitle() == null || myFeed.getTitle().length()==0) && result.ogSiteName != null){
                    dbMf.setTitle(myFeed.getId(),result.ogSiteName);
                }
                dbMf.close();

            }catch (Exception ex){
                Log.e("PostExecute",ex.getMessage() + " -- " +
                                mFeedItem.getFeedId() + " -- " +
                                mFeedItem.getLink()
                );
            }finally {
                if(dbMf.isOpen()){
                    dbMf.close();
                }
            }
    }

    private String getAttributeValue(String elementText,String attr){

        String propertyAttrib = attr + "=\"";
        String propertyValue = null;
        int propStart = elementText.indexOf(propertyAttrib);
        if (propStart != -1) {
            int propEnd = elementText.indexOf("\"", propStart + propertyAttrib.length());
            if (propEnd != -1) {
                ;
                propertyValue = elementText.substring(propStart + propertyAttrib.length(), propEnd);
            }
        }
        return propertyValue;
    }



}
